package club.hicode.spring.impl;

import club.hicode.spring.factory.AbstractBeanFactory;
import club.hicode.spring.factory.BeanDefinition;
import club.hicode.spring.info.PropertieValue;
import club.hicode.spring.info.PropertieValues;
import cn.hutool.core.util.ReflectUtil;

import java.util.List;

/**
 * 自定义的 bean 工厂
 *
 * @author Liu Chunfu
 * @date 2018-04-26 下午4:02
 **/
public class AutowiredBeanFactroy extends AbstractBeanFactory {
    @Override
    public Object createBean(BeanDefinition beanDefinition) {
        String beanClassName = beanDefinition.getBeanClassName();
        Object bean = null;
        try {
            Class<?> aClass = Class.forName(beanClassName);
            bean = aClass.newInstance();
            applyProperties(bean, beanDefinition.getValues());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }

    private void applyProperties(final Object bean, PropertieValues propertieValues) {
        List<PropertieValue> values = propertieValues.getValues();
        values.forEach(p -> ReflectUtil.setFieldValue(bean, p.getPropertyName(), p.getValue()));
    }
}
